<?php
namespace app\flash\controller;
use think\Controller;
use think\Db;
use think\Exception;
use redis\RedisPackage;
use app\flash\controller\Base;
use think\facade\Request;
// use app\controller\Base;
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: *");
header('Access-Control-Allow-Methods: POST,GET,OPTIONS');
// use common\Common;
// use common\Common;
/**
 * 功能：币世界社区的查询，评论，点赞
 * 时间：2019/08/07
 * 作者：张仕虎 
 */
class Community extends Controller
{
    /**
     * 功能：文章的查询
     * 时间：2019/08/07
     * 作者：张仕虎
     */
    public function select(){
        $state   = input('state');//查询状态 recommend-推荐  attention -关注
        $userid  = input('userid');//用户id 当状态为关注时 需要用户id
        $pagesize= input('pagesize')?input('pagesize'):20;
        $page    = input('page')?input('page'):1;
        if ($state=='recommend') {
            $headers = Request::instance()->header();
            if (@$headers['token']) {  
                $res = Db::table('friend_message')->field('id,uid,user_name,user_picture,content,picture,number,title,create_time,favour,pinglun_no')->order('create_time desc')->page($page)->paginate($pagesize,false,['query'=>request()->param()])->each(function($item,$key){
                    $user = new Base();
                    $result = Db::table('follow')->where(['userid'=>$user->user['id'],'followid'=>$item['uid']])->field('is_follw')->find();
                   
                    if (empty($result['is_follw'])) {
                        $result['is_follw'] = 0;
                    }
                    $userinfo = Db::table('user')->where('id',$item['uid'])->field('username,picture,phone')->find();
                    if (empty($userinfo['username'])) {
                        $userinfo['username'] = $userinfo['phone'];
                    }
                    $item['user_name'] = $userinfo['username'];
                    $item['user_picture'] = $userinfo['picture'];
                    $is_like = Db::table('message_like')->where(['message_id'=>$item['id'],'user_id'=>$user->user['id']])->field('id')->find();
                    $like ='';
                    if ($is_like) {
                        $like = 1;
                    }else{
                        $like = 0;
                    }
                    $item['is_like'] = $like;
                    $item['is_follw'] = $result['is_follw'];
                    $item['content']   = \json_decode($item['content'],true);
                    $item['create_time']= date("Y-m-d H:i:s",$item['create_time']);
                    if(!empty($item['picture'])){
                        $picture = explode(',',$item['picture']);
                        $item['picture'] = $picture;
                    }else{
                        $item['picture'] = [];
                    }
                    return $item;
                });
            }else{
            $res = Db::table('friend_message')->field('id,uid,user_name,user_picture,content,picture,number,create_time,favour,pinglun_no')->order('create_time desc')->page($page)->paginate($pagesize,false,['query'=>request()->param()])->each(function($item,$key){
                $item['content']   = \json_decode($item['content'],true);
                $item['create_time']= date("Y-m-d H:i:s",$item['create_time']);
                $userinfo = Db::table('user')->where('id',$item['uid'])->field('username,picture,phone')->find();
                    if (empty($userinfo['username'])) {
                        $userinfo['username'] = $userinfo['phone'];
                    }
                    $item['user_name'] = $userinfo['username'];
                    $item['user_picture'] = $userinfo['picture'];
                $item['is_follw']   = 0;
                $item['is_like']    = 0;
                if(!empty($item['picture'])){
                    $picture = explode(',',$item['picture']);
                    $item['picture'] = $picture;
                }else{
                    $item['picture'] = [];
                }
                return $item;
            });
          }
        }else if ($state=='attention') {
            $user = new Base();
            if (empty($userid)) {
                return json(msg(0, '', '用户id不存在'));
            }
            $where = "userid=$userid and is_follw=1 and followid!=$userid";
            $data = Db::table('follow')->where($where)->all();
            if (empty($data)) {
                return json(msg(0, '', '还没有关注!'));
            }
            $followid = implode(',', array_column($data, 'followid'));
            $res = Db::table('friend_message')->wherein('uid',$followid)->field('id,uid,user_name,user_picture,content,picture,number,create_time,favour,pinglun_no')->order('create_time desc')->page($page)->paginate($pagesize,false,['query'=>request()->param()])->each(function($items,$key){
                $items['content']   = \json_decode($items['content'],true);
                $items['create_time']= date("Y-m-d H:i:s",$items['create_time']);
                $user = new Base();
                $result = Db::table('follow')->where(['userid'=>$user->user['id'],'followid'=>$items['uid']])->field('is_follw')->find();
                   
                    if (empty($result['is_follw'])) {
                        $result['is_follw'] = 0;
                      }
                $is_like  = Db::table('message_like')->where(['message_id'=>$items['id'],'user_id'=>$user->user['id']])->field('id')->find();
                if ($is_like) {
                    $items['is_like'] = 1;
                }else{
                    $items['is_like'] = 0;
                }
                $userinfo = Db::table('user')->where('id',$items['uid'])->field('username,picture,phone')->find();
                    if (empty($userinfo['username'])) {
                        $userinfo['username'] = $userinfo['phone'];
                    }
                    $items['user_name'] = $userinfo['username'];
                    $items['user_picture'] = $userinfo['picture'];
                $items['is_follw'] = $result['is_follw'];
                $items['count_data'] = Db::table('comment')->where(['message_id'=>$items['id'],'flag'=>3])->count();
                if(!empty($items['picture'])){
                    $picture = explode(',',$items['picture']);
                    $items['picture'] = $picture;
                }else{
                    $items['picture'] = [];
                }
                // var_dump($items);
               return $items;
                
            });
        }else{
            return json(msg(0, '', '查询状态不合法'));
        }
        return json(msg(1, $res, '数据返回成功'));
        /*if ($res) {
            return json(msg(1, $res, 'message'));
        }else{
            return json(msg(0, $res, '无数据'));
        }*/
    }
    /**
     * 社区文章用户详情
     * 2019/08/21
     * 张仕虎
     */
    public function userdatelist(){
        $userid = input('userid');
        if (empty($userid)) {
            return json(msg(0,'','用户信息不存在'));
        }
        $headers = Request::instance()->header();
            if (@$headers['token']) {
                $user = new Base();
                $userdata = Db::table('user')->where('id',$userid)->field('id,username,phone,picture')->find();
            if (!$userdata) {
                return json(msg(0,'','用户不存在'));
            }
            if (empty($userdata['username'])) {
                $userdata['username'] = $userdata['phone'];
            }
            $fans = Db::table('follow')->where(['followid'=>$userdata['id'],'is_follw'=>1])->count();
            $attention = Db::table('follow')->where(['userid'=>$userdata['id'],'is_follw'=>1])->count();
            $result = Db::table('follow')->where(['userid'=>$user->user['id'],'followid'=>$userdata['id']])->field('is_follw')->find();        
             if (empty($result['is_follw'])) {
                $result['is_follw'] = 0;
             }
             $userdata['fans'] = $fans;
            $userdata['attention'] = $attention;
            $userdata['is_follw']   = $result['is_follw'];
            unset($fans);
            unset($attention);
            return json(msg(1,$userdata,'查询成功'));
        }else{
        $userdata = Db::table('user')->where('id',$userid)->field('id,username,phone,picture')->find();
        if (!$userdata) {
            return json(msg(0,'','用户不存在'));
        }
        if (empty($userdata['username'])) {
            $userdata['username'] = $userdata['phone'];
        }
        $fans = Db::table('follow')->where(['followid'=>$userdata['id'],'is_follw'=>1])->count();
        $attention = Db::table('follow')->where(['userid'=>$userdata['id'],'is_follw'=>1])->count();
        $userdata['fans'] = $fans;
        $userdata['attention'] = $attention;
        $userdata['is_follw']   = 0;
        unset($fans);
        unset($attention);
        return json(msg(1,$userdata,'查询成功'));
       }
    }
    /**
     * 功能：币圈的搜索
     * 时间：2019/08/26
     * 作者：张仕虎
     */
    public function communitysearch(){
        $search = trim(input('search')); 
        $headers = Request::instance()->header();
        if (@$headers['token']) {
            $user = new Base();
            $where[] = ['username','like',"%$search%"];
            $data = Db::table('user')->where($where)->field('id,username,phone,picture')->select();
            $follow = '';
            foreach ($data as $k => $v) {
                if ($v['id']==$user->user['id']) {
                    unset($data[$k]);
                }
                 $follow = Db::table('follow')->where(['userid'=>$user->user['id'],'followid'=>$v['id']])->field('is_follw')->find();
                $data[$k]['is_follw'] = $follow['is_follw'];
            }
            
            $arr = Db::table('friend_message')->order('create_time desc')->field('id,uid,user_name,user_picture,content,picture,favour,create_time,pinglun_no')->select();
            foreach ($arr as $key => $value) {
                $follow = Db::table('follow')->where(['userid'=>$user->user['id'],'followid'=>$value['uid']])->find();
                if (empty($follow)) {
                    $follow['is_follw'] = 0;
                }
                $arr[$key]['is_follw'] = $follow['is_follw'];
                $arr[$key]['content'] = json_decode($value['content'],true);
                $arr[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
                $is_like  = Db::table('message_like')->where(['message_id'=>$value['id'],'user_id'=>$user->user['id']])->field('id')->find();
                if ($is_like) {
                    $arr[$key]['is_like'] = 1;
                }else{
                    $arr[$key]['is_like'] = 0;
                }
                if(!empty($value['picture'])){
                    $picture = explode(',',$value['picture']);
                    $arr[$key]['picture'] = $picture;
                }else{
                    $arr[$key]['picture'] = [];
                }
                if (!strstr($arr[$key]['content'],$search)) {
                    unset($arr[$key]);
                }
            }
            return json(msg(1,['userinfo'=>$data,'community'=>array_values($arr)],'查询成功'));
        }else{
            $where[] = ['username','like',"%$search%"];
            $data = Db::table('user')->where($where)->field('id,username,phone,picture')->select();
            foreach ($data as $key => $value) {
                 $data[$key]['is_follw'] = 0;
            }
            $arr = Db::table('friend_message')->order('create_time desc')->field('id,uid,user_name,user_picture,content,picture,favour,create_time,pinglun_no')->select();
            foreach ($arr as $k => $v) {
                $arr[$k]['is_follw'] = 0;
                $arr[$k]['content'] = json_decode($v['content'],true);
                $arr[$k]['create_time'] = date("Y-m-d H:i:s",$v['create_time']);
                $arr[$k]['is_like'] = 0;
                if(!empty($v['picture'])){
                    $picture = explode(',',$v['picture']);
                    $arr[$k]['picture'] = $picture;
                }else{
                    $arr[$k]['picture'] = [];
                }
                if (!strstr($arr[$k]['content'],$search)) {
                    unset($arr[$k]);
                }
            }
            
            // return json(msg(1,'','查询成功'));
           return json(msg(1,['userinfo'=>$data,'community'=>array_values($arr)],'查询成功'));
        }
    }
    /**
     * 查询个人动态
     * 2019/08/21
     * 张仕虎
     */
    public function finddynamic(){
        $user_id = input('userid');
        $pagesize= input('pagesize')?input('pagesize'):20;
        $page    = input('page')?input('page'):1;
        if (empty($user_id)) {
            return json(msg(0,'','用户信息不存在'));
        }
        $headers = Request::instance()->header();
        if (@$headers['token']) {
            $data = Db::table('friend_message')->where('uid',$user_id)->field('id,uid,user_name,user_picture,content,picture,favour,create_time,pinglun_no')->order('create_time desc')->page($page)->paginate($pagesize,false,['query'=>request()->param()])->each(function($item,$key){
                $user = new Base();
                    $is_like = Db::table('message_like')->where(['message_id'=>$item['id'],'user_id'=>$user->user['id']])->field('id')->find();
                    $like ='';
                    if ($is_like) {
                        $like = 1;
                    }else{
                        $like = 0;
                    }
                    $userinfo = Db::table('user')->where('id',$item['uid'])->field('username,phone,picture')->find();
                    if (empty($userinfo['username'])) {
                        $userinfo['username'] = $userinfo['phone'];
                    }
                    $item['user_name'] = $userinfo['username'];
                    $item['user_picture'] = $userinfo['picture'];
                    if(!empty($item['picture'])){
                        $picture = explode(',',$item['picture']);
                        $item['picture'] = $picture;
                    }else{
                        $item['picture'] = [];
                    }
                    $item['is_like'] = $like;
                    $item['content'] = json_decode($item['content'],true);
                    $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);
                    return $item;
            });
            return json(msg(1,$data,'查询成功'));
        }else{
            $data = Db::table('friend_message')->where('uid',$user_id)->field('id,uid,user_name,user_picture,content,picture,favour,create_time,pinglun_no')->page($page)->paginate($pagesize,false,['query'=>request()->param()])->each(function($item,$key){
                $userinfo = Db::table('user')->where('id',$item['uid'])->field('username,phone,picture')->find();
                    if (empty($userinfo['username'])) {
                        $userinfo['username'] = $userinfo['phone'];
                    }
                    $item['user_name'] = $userinfo['username'];
                    $item['user_picture'] = $userinfo['picture'];
                if(!empty($item['picture'])){
                    $picture = explode(',',$item['picture']);
                    $item['picture'] = $picture;
                }else{
                    $item['picture'] = [];
                }
                $item['is_like']  = 0;
                $item['content'] = json_decode($item['content'],true);
                $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);
                return $item;
            });
            
        return json(msg(1,$data,'查询成功'));
         }
    }
    /**
     * 社区热门推荐查询
     * 2019/08/21
     * 张仕虎
     */
    public function hotrecommend(){
        $headers = Request::instance()->header();
        if (@$headers['token']) {
            $user = new Base();
            $data = Db::table('user')->where('id','neq',$user->user['id'])->field('id,username,phone,picture')->select();
            $count = [];
            foreach ($data as $key => $value) {
                $arr = Db::table('follow')->where(['followid'=>$value['id'],'userid'=>$user->user['id']])->field('is_follw')->find();
                $count = count($arr);
                $data[$key]['count'] = $count;
                $res = '';
                if (empty($data[$key]['username'])) {
                    $data[$key]['username'] = $data[$key]['phone'];
                }
                if ($data[$key]['count']>10) {
                    unset($data[$key]);
                }
                if (empty($arr['is_follw'])) {
                    $arr['is_follw'] = 0;
                }
                $data[$key]['is_follw'] = $arr['is_follw'];
                if ($data[$key]['is_follw']==1) {
                    unset($data[$key]);
                }
                $res =  array_slice($data,0,10);
            }
            return json(msg(1,$res,'查询成功'));
        }else{
        $data = Db::table('user')->field('id,username,phone,picture')->select();
        $count = [];
        $res = '';
        foreach ($data as $key => $v) {
            $count = Db::table('follow')->where(['followid'=>$v['id']])->count();
            $data[$key]['count'] = $count;
            if (empty($data[$key]['username'])) {
                $data[$key]['username'] = $data[$key]['phone'];
            }
            if ($data[$key]['count']>10) {
                unset($data[$key]);
            }
            $data[$key]['is_follw'] = 0;
           $res =  array_slice($data,0,10);
        }
        return json(msg(1,$res,'查询成功'));
    }
       
    }
    /**
     * 社区币圈号
     * 2019/08/21
     * 张仕虎
     */
    public function author(){
        $status = input('status');//查询类型 1-我得关注 2-推荐
        if ($status==1) {
            $user = new Base();
            $data = Db::table('follow')->where(['userid'=>$user->user['id'],'is_follw'=>1])->field('followid,is_follw')->select();
            $arr = array();
            foreach ($data as $key => $v) {
                $res = Db::table('user')->where('id',$v['followid'])->field('id,username,phone,picture,rand_id')->find(); 
                if (empty($res['username'])) {
                    $res['username'] = $res['phone'];                  
                }
                unset($res['phone']);
                $arr[] = $res; 
                $arr[$key]['is_follw'] = $data[$key]['is_follw'];
            }
            // var_dump($arr);
            return json(msg(1,$arr,'查询成功'));
        }elseif ($status==2) {
            $headers = Request::instance()->header();
            if (@$headers['token']) {
                $user = new Base();
                $data = Db::table('user')->where('id','neq',$user->user['id'])->field('id,username,phone,picture,rand_id')->select(); 
            foreach ($data as $k => $v) {   
                $res = Db::table('follow')->where(['userid'=>$user->user['id'],'followid'=>$v['id']])->field('is_follw')->find();                
                if (empty($res['is_follw'])) {
                    $res['is_follw'] = 0;
                }
                // $arr[] = $v;
                 $data[$k]['is_follw'] = $res['is_follw'];
                 if (empty($v['username'])) {
                     $data[$k]['username'] = $v['phone'];
                     
                 }
                 unset($v['phone']);
                // // $data[$k]['is_follw'] = $res['is_follw'];
                if ($data[$k]['is_follw']==1) {
                    unset($data[$k]);
                }  
            }
            $arr = array_values($data);
            return json(msg(1,$arr,'查询成功'));
            }else{
                $data = Db::table('user')->field('id,username,phone,picture,rand_id')->select();
                foreach ($data as $key => $v) {
                   $data[$key]['is_follw'] = 0;
                   if (empty($v['username'])) {
                       $data[$key]['username'] = $v['phone'];                  
                   }
                   unset($v['phone']);
                }
                return json(msg(1,$data,'查询成功'));
            }    
        }
    }
    /**
     * 功能：社区文章点赞
     * 时间：2019/08/07
     * 作者：张仕虎
     */
    public function likecount(){
        $user_id        = input('user_id');//用户id
        $status         = input('status');//点赞状态 0-取消赞 1-点赞
        $cid            = input('cid');//app软件唯一标识
        $type           = input('type');//点赞类型 1-文章点赞 2-评论点赞
        $type_id        = input('type_id');//对应的文章或评论的id
        $create_time    = strtotime(date('Y-m-d H:i:s'));
        if ($type==1) {
            if ($status==1) {
                $data = Db::table('friend_like')->where(['user_id'=>$user_id,'type_id'=>$type_id,'type'=>$type])->whereOr(['cid'=>$cid])->find();
                if ($data) {
                    return json(msg(0, '', '已经点过了'));
                }
                $arr = array(
                    'user_id'    => $user_id,
                    'type_id'    => $type_id,
                    'type'       => $type,
                    'cid'        => $cid,
                    'create_time'=> $create_time
                );
                $result = Db::table('friend_like')->insert($arr);
                if (!$result) {
                    return json(msg(0, '', '点赞失败'));
                }
                $res  = Db::table('friend_message')->where('id',$type_id)->setInc('favour');
            }else{
                $data = Db::table('friend_message')->where('id',$type_id)->find('favour');
                if ($data['favour']==0) {
                    return json(msg(0, '', '不能再取消了'));
                }
                $result = Db::table('friend_like')->where(['type_id'=>$type_id,'user_id'=>$user_id,'type'=>$type])->whereOr(['cid'=>$cid])->delete();
                if (!$result) {
                    return json(msg(0, '', '取消失败'));
                }
                $res = Db::table('friend_message')->where('id',$type_id)->setDec();
            }
        }else{
            if ($status==1) {
                $data = Db::table('friend_like')->where(['user_id'=>$user_id,'type_id'=>$type_id,'type'=>$type])->whereOr(['cid'=>$cid])->find();
                if ($data) {
                    return json(msg(0, '', '已经点过了'));
                }
                $arr = array(
                    'user_id'    => $user_id,
                    'type_id'    => $type_id,
                    'type'       => $type,
                    'cid'        => $cid,
                    'create_time'=> $create_time
                );
                $result = Db::table('friend_like')->insert($arr);
                if (!$result) {
                    return json(msg(0, '', '点赞失败'));
                }
                $res  = Db::table('friend_comment')->where('id',$type_id)->setInc('like_count');
            }else{
                $data = Db::table('friend_comment')->where('id',$type_id)->find('like_count');
                if ($data['like_count']==0) {
                    return json(msg(0, '', '不能再取消了'));
                }
                $result = Db::table('friend_like')->where(['type_id'=>$type_id,'user_id'=>$user_id,'type'=>$type])->whereOr(['cid'=>$cid])->delete();
                if (!$result) {
                    return json(msg(0, '', '取消失败'));
                }
                $res = Db::table('friend_comment')->where('id',$type_id)->setDec();
            }

            if ($res) {
                return json(msg(1, '', '点赞成功'));
            }else{
                return json(msg(0, '', '点赞失败'));
            }
        }
    }
}